import json
import logging
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.conf import settings
from .models import TechInsight
from .serializers import (
    TechInsightSerializer,
    TechInsightCreateSerializer,
    TechInsightListSerializer
)
from dify.api import run_workflow, parse_workflow_response

logger = logging.getLogger(__name__)

class TechInsightViewSet(viewsets.ModelViewSet):
    """技术洞察视图集"""
    permission_classes = [IsAuthenticated]
    queryset = TechInsight.objects.filter(is_active=True)
    
    def get_serializer_class(self):
        if self.action == 'create':
            return TechInsightCreateSerializer
        elif self.action == 'list':
            return TechInsightListSerializer
        return TechInsightSerializer
    
    @action(detail=False, methods=['post'])
    def generate(self, request):
        """生成技术洞察"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        try:
            industry = serializer.validated_data.get('industry')
            keyword = serializer.validated_data.get('keyword')
            
            # 调用 Dify API 生成内容
            response = run_workflow(
                workflow_name="技术洞察",
                inputs={
                    "industry": industry,
                    "keyword": keyword
                },
                user=str(request.user.id)
            )
            
            content = parse_workflow_response(response)
            
            # 创建洞察记录
            insight = TechInsight.objects.create(
                title=f"{industry}-{keyword}技术洞察",
                industry=industry,
                keyword=keyword,
                insight_content=content,
                user=request.user
            )
            
            return Response({
                'code': 200,
                'message': '生成成功',
                'data': TechInsightSerializer(insight).data
            })
            
        except Exception as e:
            logger.error(f"生成失败: {str(e)}", exc_info=True)
            return Response({
                'code': 500,
                'message': f'生成失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['get'])
    def industry(self, request):
        """按行业查询技术洞察"""
        try:
            industry = request.query_params.get('industry')
            if not industry:
                return Response({
                    'code': 400,
                    'message': '请提供行业参数'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            insights = TechInsight.objects.filter(industry=industry)
            serializer = TechInsightListSerializer(insights, many=True)
            
            return Response({
                'code': 200,
                'message': '查询成功',
                'data': {
                    'list': serializer.data,
                    'total': len(serializer.data),
                    'empty_tip': '暂无相关洞察' if not serializer.data else None
                }
            })
            
        except Exception as e:
            logger.error(f"查询失败: {str(e)}")
            return Response({
                'code': 500,
                'message': f'查询失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def _process_dify_response(self, response_text):
        """处理Dify响应"""
        thought_content = None
        reference_docs = []
        last_two_messages = []
        
        # 按行解析响应，只保留最后两条消息
        for line in response_text.split('\n'):
            if not line.strip():
                continue
                
            try:
                data = json.loads(line)
                event = data.get('event')
                
                # 只关注 agent_thought 和 message_end 事件
                if event in ['agent_thought', 'message_end']:
                    last_two_messages.append(data)
                    if len(last_two_messages) > 2:
                        last_two_messages.pop(0)
                        
            except json.JSONDecodeError:
                continue
        
        # 处理最后两条消息
        for message in last_two_messages:
            event = message.get('event')
            
            if event == 'agent_thought':
                thought_content = message.get('thought')
                
            elif event == 'message_end':
                metadata = message.get('metadata', {})
                resources = metadata.get('retriever_resources', [])
                for resource in resources:
                    reference_docs.append({
                        'document_name': resource.get('document_name'),
                        'content': resource.get('content')
                    })
        
        return {
            'thought': thought_content,
            'references': reference_docs
        }

    @action(detail=False, methods=['post'])
    def initialize(self, request):
        """初始化行业技术洞察"""
        try:
            # 获取行业和关键词数据
            insights_data = request.data.get('insights', [])
            
            results = []
            for data in insights_data:
                industry = data['industry']
                keyword = data['keyword']
                
                try:
                    # 调用 Dify API
                    logger.info(f"开始处理 {industry} - {keyword}")
                    
                    response = run_workflow(
                        workflow_name="技术洞察",
                        inputs={
                            "industry": industry,
                            "keyword": keyword
                        },
                        user=str(request.user.id)
                    )
                    
                    # 解析响应
                    content = parse_workflow_response(response)
                    logger.info(f"Dify 响应内容: {content}")
                    
                    # 保存到数据库
                    insight = TechInsight.objects.create(
                        title=f"{industry}-{keyword}技术洞察",
                        industry=industry,
                        keyword=keyword,
                        insight_content=content,
                        user=request.user
                    )
                    
                    results.append({
                        'industry': industry,
                        'keyword': keyword,
                        'status': 'success'
                    })
                    
                except Exception as e:
                    logger.error(f"{industry}-{keyword} 处理失败: {str(e)}")
                    results.append({
                        'industry': industry,
                        'keyword': keyword,
                        'status': 'failed',
                        'error': str(e)
                    })
            
            return Response({
                'code': 200,
                'message': '初始化成功，任务处理中',
                'data': {
                    'results': results
                }
            })
            
        except Exception as e:
            logger.error(f"初始化失败: {str(e)}")
            return Response({
                'code': 500,
                'message': f'初始化失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['get'])
    def search(self, request):
        """搜索技术洞察"""
        try:
            industry = request.query_params.get('industry')
            keyword = request.query_params.get('keyword')
            
            queryset = TechInsight.objects.all()
            
            if industry:
                queryset = queryset.filter(industry=industry)
            if keyword:
                queryset = queryset.filter(insight_content__icontains=keyword)
                
            serializer = TechInsightListSerializer(queryset, many=True)
            
            return Response({
                'code': 200,
                'message': '查询成功',
                'data': serializer.data
            })
            
        except Exception as e:
            logger.error(f"查询失败: {str(e)}")
            return Response({
                'code': 500,
                'message': f'查询失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
